package com.changwu.cwbase.bean.model;

import android.app.Activity;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.changwu.cwbase.App;
import com.changwu.cwbase.Constants;
import com.changwu.cwbase.bean.entity.User;
import com.changwu.cwbase.event.LogoutEvent;
import com.changwu.cwbase.util.PreferencesUtil;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by Administrator on 2016/9/23.
 */

public class UserModel {
    private static UserModel instance = new UserModel();
    private User userModel;

    public static UserModel getInstance() {
        return instance;
    }

    public UserModel() {
        if (userModel == null) {
            initUserInfo();
        }
    }

    /**
     * 重新登陆后重新加载用户session信息
     */
    public void initUserInfo() {
        String temp = PreferencesUtil.getStringData("user", "");
        if (!TextUtils.isEmpty(temp)) {
            userModel = JSON.parseObject(temp, User.class);
        } else {
            userModel = new User();
        }
    }


    public User getModel() {
        return userModel;
    }

    public String getMobile() {
        return userModel.mobile;
    }

    public String getToken() {
        return PreferencesUtil.getStringData(Constants.TOKEN, "");
    }

    public String getUid() {
        return userModel.uid + "";
    }

    /**
     * 用户是否登陆
     *
     * @return
     */
    public boolean isLogin() {
        boolean flag = false;
        if (!TextUtils.isEmpty(getToken())) {
            flag = true;
        }
        return flag;
    }


    public void exitLogin() {
        PreferencesUtil.saveStringData("user", "");
        userModel = new User();
        App.getInstance().exit();
        EventBus.getDefault().post(new LogoutEvent());
    }

    public void exitLogin(Activity activity) {
        PreferencesUtil.saveStringData("user", "");
        PreferencesUtil.saveStringData(Constants.TOKEN, "");
        userModel = new User();
        App.getInstance().exit();
//        IntentUtil.startActivity(activity, LoginActivity.class);
        EventBus.getDefault().post(new LogoutEvent());
    }
}